<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class OAuthUser extends Model
{
    use HasFactory;

    protected $table = 'oauth_users';

    protected $fillable = [
        'user_id',
        'provider',
        'oauth_id',
        'unionid',
        'name',
        'email',
        'avatar',
        'pid',
        'cid',
    ];

    /**
     * OAuth user.
     *
     * @return  \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Provider condition.
     *
     * @param Builder $builder
     * @param string $provider
     *
     * @return  Builder
     */
    public function scopeOfProvider(Builder $builder, $provider)
    {
        return $builder->where('provider', $provider);
    }

    /**
     * Provider condition.
     *
     * @param Builder $builder
     * @param string $id
     *
     * @return  Builder
     */
    public function scopeOfOAuthId(Builder $builder, $id)
    {
        return $builder->where('oauth_id', $id);
    }

    /**
     * Register oauth user.
     *
     * @return  $this
     */
    public function register(
        int    $userId,
        string $provider,
        string $oauthId,
        string $name,
        string $email = null,
        string $avatar = null,
        string $unionId = null
    )
    {
        return $this->create(array_filter([
            'user_id' => $userId,
            'provider' => $provider,
            'oauth_id' => $oauthId,
            'name' => $name ?? '',
            'email' => $email,
            'avatar' => $avatar,
            'unionid' => $unionId,
        ]));
    }

    /**
     * Find user by wechat union id.
     *
     * @param string $unionid
     *
     * @return  \Illuminate\Support\Collection|null
     */
    public function findByUnionid(string $unionid)
    {
        return $this->ofProvider('wechat')
            ->where('unionid', $unionid)
            ->first();
    }
}
